package com.ghp.search.job.once;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ghp.search.model.entity.Post;
import com.ghp.search.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author ghp
 * @date 2023/5/28
 * @title 获取初始化文章列表数据
 * @description 每次项目启动都会通过Rest请求获取第三方接口的数据，然后保存到数据库
 */
//@Component
@Slf4j
public class FetchInitPostList implements CommandLineRunner {
    @Autowired
    private PostService postService;

    @Override
    public void run(String... args) throws Exception {
        // 1、获取数据
        // POST请求
        String json = "{\"current\":1,\"pageSize\":8,\"sortField\":\"createTime\",\"sortOrder\":\"descend\",\"category\":\"文章\",\"reviewStatus\":1}";
        String url = "https://www.code-nav.cn/api/post/search/page/vo";
        String result = HttpRequest
                .post(url)
                .body(json)
                .execute()
                .body();

        // 2、解析JSON
        Map<String, Object> map = JSONUtil.toBean(result, Map.class);
        JSONObject data = (JSONObject) map.get("data");
        JSONArray records = (JSONArray) data.get("records");
        List<Post> postList = new ArrayList<>(10);
        for (Object record : records) {
            JSONObject p = (JSONObject) record;
            Post post = new Post();
            post.setTitle(p.getStr("title"));
            post.setContent(p.getStr("content"));
            JSONArray tags = (JSONArray) p.get("tags");
            List<String> tagList = tags.toList(String.class);
            post.setTags(JSONUtil.toJsonStr(tagList));
            post.setUserId(1L);
            postList.add(post);
        }

        // 3、数据入库
        boolean flag = postService.saveBatch(postList);
        if (flag){
            log.info("FetchInitPostList执行成功，新增文章记录数: {}", postList.size());
        }else{
            log.error("FetchInitPostList执行失败！");
        }
    }
}
